﻿#include "main_widget.h"

#include <QApplication>
#include <QFile>
#include "easylogging++.h"
#include "util_tools.h"
#include "sqlite_manager.h"

INITIALIZE_EASYLOGGINGPP

void createWorkDirs()
{
    UtilTools::makeDir(QString("data"));
    UtilTools::makeDir(QString("logs"));
}

void createDb()
{
    SqliteManager *s = new SqliteManager;
    // 执行数据库脚本
    QFile sqlFile(":/resources/sql/create_table_v1.sql");
    sqlFile.open(QIODevice::ReadOnly);
    QString sql = sqlFile.readAll();
    sqlFile.close();
    QStringList sqlList = sql.split(";");
    foreach(sql, sqlList) {
        // SQL脚本中多个SQL语句之间可能存在空行或空格，此处将全是空SQL进行过滤
        sql = sql.trimmed();
        if (sql.isEmpty()) {
            continue;
        }

        bool ret = s->exec(sql);
        if (!ret)
        {
            LOG(ERROR) << "sql: " << sql.toStdString();
            LOG(ERROR) << "execute sql failed, error info: " << s->lastError().toStdString();
        }
    }
}

void initLogConfig()
{
    // Load configuration from file
    el::Configurations conf("config/log.conf");
    // Reconfigure single logger
    el::Loggers::reconfigureLogger("default", conf);
    // Actually reconfigure all loggers instead
    el::Loggers::reconfigureAllLoggers(conf);
    // Now all the loggers will use configuration from file
}

int main(int argc, char *argv[])
{
    createWorkDirs();
    createDb();
    initLogConfig();

    QString startCommand = argv[0];
    for (int i = 0; i < argc; i++)
    {
        startCommand += " ";
        startCommand += argv[i];
    }

    QApplication a(argc, argv);
    a.setWindowIcon(QIcon(":/resources/images/app.png"));

    MainWidget w;
    w.show();

    return a.exec();
}
